package com.example.demo.config;

import com.alibaba.druid.support.json.JSONUtils;
import com.example.demo.util.MyException;
import com.example.demo.util.Result;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义异常处理器
 */
@RestControllerAdvice
public class ControllerHandler {

    @ExceptionHandler(MyException.class)
    @ResponseBody
    public Result myException(MyException e) {
        return e.getResult() != null ? e.getResult() : Result.error(e.getResultCode());
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result methodArgumentNotValidExceptionHandler(BindException bindException) {
        List<FieldError> fieldErrors = bindException.getBindingResult().getFieldErrors();
        List<String> list = null;
        if (!CollectionUtils.isEmpty(fieldErrors)) {
            list = fieldErrors.stream().map(fieldError -> fieldError.getDefaultMessage()).collect(Collectors.toList());
        }
        return Result.error(JSONUtils.toJSONString(list));
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result ExceptionHandler(Exception exception) {
        return Result.error(exception.getMessage());
    }
}
